package com.xlinur.moviegrabber;

import java.util.Collections;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GrabberImdb extends Grabber {

	@SuppressWarnings("serial")
	GrabberImdb() {
		mUriSearch = "http://m.imdb.com/find?q={1}&button=Search";
		mUriItem = "http://m.imdb.com/title/{1}/";
		mEncoding = "UTF-8";
		mPrefix = "imdb.com:";
		mXpathListItem = "/body/section[@class='posters']/div[@class='poster ']/div[@class='label']/div[@class='title']/a";
		mXpathItem = Collections.unmodifiableMap(new HashMap<String, String>(
				10, 1.0f) {
			{
				put("!title,year!~ !![\\)\\(]",
						"/body/section[@class='overview']/div[@class='mainInfo']/h1[1]");
				put("director", "/body/section[@class='topCrew']/div[1]/p[1]");
				put("actors",
						"/body/section[@class='topCast posters']/div[@class='poster ']/div[@class='label']/div[@class='title']/a");
				put("ext_rate",
						"/body/section[@class='overview']/div[@class='mainInfo']/div[@class='votes']/strong[1]");
				put("details", "/body/section[@class='details']");
			}
		});
	}

	protected String formatLength(String str) {
		// 1 hr 44 mins
		String result = str.replace("mins", "").replace("min", "").replace("hrs", "hr");
		String[] resArr = result.split("hr");
		if (resArr.length > 1) {
			result = String.valueOf(Integer.parseInt(resArr[0].trim()) * 60
					+ Integer.parseInt(resArr[1].trim()));
		} else {
			result = resArr[0].trim();
		}
		return result;
	}

	public HashMap<String, String> getItem(String id) {
		HashMap<String, String> result = super.getItem(id);
		String details = result.get("details");
		result.remove("details");
		Pattern genrePattern = Pattern.compile(".*^Genre.\n(.*?)\n.*",Pattern.DOTALL+Pattern.MULTILINE);
		Matcher genreMatch = genrePattern.matcher(details);
		if (genreMatch.find() && genreMatch.groupCount()>0){
			result.put("genre", genreMatch.group(1).trim());
		}
		Pattern descriptionPattern = Pattern.compile(".*Plot.Summary(.*?)Full.Summary.*",Pattern.DOTALL+Pattern.MULTILINE);
		Matcher descriptionMatch = descriptionPattern.matcher(details);
		if (descriptionMatch.find()){
			result.put("description", descriptionMatch.group(1).trim());
		}
		Pattern lengthPattern = Pattern.compile(".*^Run.time.\n(.*?)\n.*",Pattern.DOTALL+Pattern.MULTILINE);
		Matcher lengthMatch = lengthPattern.matcher(details);
		if (lengthMatch.find()){
			result.put("length", this.formatLength(lengthMatch.group(1).trim()));
		}
		return result;
	}
}